//
//  MessageController.swift
//  SchoolDemo
//
//  Created by rimi on 16/9/26.
//  Copyright © 2016年 YQ. All rights reserved.
//

import UIKit
/*
 表格视图的性能优化（性能调优）
 1所有的图片不要使用原生的裁剪圆角模式
 2尽量不要使用透明设置
 3所有参数提前准备好，在需要的时候直接获取使用
 4包括视图尽量不要使用延时加载，都提前准备好
 */
class MessageController: HSBasicController {

    //消息列表视图模型
    let messageListVM = HSMessageListviewModal()
    //输入工具栏
    var inputToolBarV: UIView!
    //文本输入框
    var inputTextF: UITextField!
    //记录键盘状态
    var isKeyboardShow = false
    //记录当前点击按钮对应的cell
    var currentCell = HSMessageTableViewCell()
    //当前编辑的cell
    var currentEditCellIndexPath: IndexPath!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //注册原型cell
        tableView.register(UINib(nibName:"HSMessageTableViewCell",bundle: nil), forCellReuseIdentifier: "messageCell")
        tableView.estimatedRowHeight = 200
        //如果实现了自定义行高，下面这句代码就不需要
        tableView.rowHeight = UITableViewAutomaticDimension
        //添加右边添加消息按钮
        let rightBtn = UIBarButtonItem(imageName: "release_msg_nor", bgImageName: "release_msg_press", target: self, action: #selector(rightBtnClicked))
        navigationItem.rightBarButtonItem = rightBtn
        //加载数据
        loadData()
        //添加输入工具条
        inputTextView()
        //注册监听键盘的弹出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(notificationWithKeyboard(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    //右边按钮的监听回调
    @objc fileprivate func rightBtnClicked() {
        let releseVc = HSReleaseInfoController()
        //隐藏标签栏
        releseVc.hidesBottomBarWhenPushed = true
            
        navigationController?.pushViewController(releseVc, animated: true)
    }
    
    //加载数据
    override func loadData() {
        refreshC.beginRefreshing()
        //获得刷新类型
        let loType = isPull ? MessageLoadType.pull : MessageLoadType.drop
      //请求数据
        messageListVM.requestMessage(loadType: loType){
            [weak self] (err,isRefresh) in
            //关闭刷新控件
            self?.refreshC.endRefreshing()
            //记录刷新状态
            self?.isPull = false
            //判断是否刷新视图
            if err != nil {
                return
            }
            if isRefresh {
                //刷新视图
                self?.tableView.reloadData()
            }
        }
        //设置行高
        //实现这个方法 要关闭   tableView.rowHeight = UITableViewAutomaticDimension
//        func tableview(_ tableView: UITableView,heightForRowAtindexPath: IndexPath) -> CGFloat {
//            let messageVM = messageListVM.messages[IndexPath.row]
//            //返回计算好的高度 缓存在模型中高度
//            return messageVM.cellHeight
//        }
    }
   
}



    // MARK: - Table view data source
extension MessageController {

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return messageListVM.messages.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! HSMessageTableViewCell
        
        //获得对应的视图模型
        let messageVM = messageListVM.messages[indexPath.row]
        //传递模型给cell
        cell.messageVM = messageVM
        
        //获得按钮的回调闭包
        cell.likeBtnCallback = {[weak self] (clickCell) -> () in
            print("点赞",clickCell)
            self?.clickedSupportBtnWithCell(clickCell as! HSMessageTableViewCell)
        
        }
        //点赞
        
        //获得回复按钮的闭包事件
        cell.replauBtnCallback = {[weak self](clickCell) -> () in
          
            self?.replayBtnClicked(cell: clickCell as! HSMessageTableViewCell)
        }
        
        return cell
    }
  
}
//MARK:  - 点赞回复相关功能
extension MessageController {
    
    //MARK： - 点赞按钮
    func clickedSupportBtnWithCell(_ cell: HSMessageTableViewCell) {
        //获得对应的模型
        currentEditCellIndexPath = tableView.indexPath(for: cell)!
        let messageVM = messageListVM.messages[currentEditCellIndexPath.row]
        //判断是否已经点赞
//        
//        if cell.messageLikeBtn.isSelected {
//         HSAlertView.bottomAlertView("你已经点赞了")
//        }
        
        //发送数据给服务器
        let url = "ZH-schoolname-S-submitJXLike"
        let key = userInfo["key"] ?? ""
        let notifyId = messageVM.message.not_id
        let likedataDict = ["key":key,"id":notifyId,"user_type":2]
        
        HSNetWorkTools.shared.downloadData(url: url, parameters: likedataDict) {[weak self] (data, err) in
            guard let data = data as? NSDictionary else {
                 HSAlertView.bottomAlertView("网络连接异常")
                
                return
            }
            switch data["result"] as! Int {
            case 0:
                if let likeArray = data["data"] as? NSArray {
                    //从服务器返回
                    let likeDict = likeArray.firstObject as! NSDictionary
                    //刷新模型数据
                    let newMessage = messageVM.message
                    newMessage.likelist = likeDict["likelist"] as? String
                    newMessage.likenum = likeDict["likenum"] as! Int
                    messageVM.message = newMessage
                    //刷新视图
                    self?.tableView.reloadRows(at: [(self?.currentEditCellIndexPath)!], with: .automatic)
                }
            case 1:
                  HSAlertView.bottomAlertView("您已经点过了")
            default:
                break
                
            }
        }
    }
    
    
    
    ///输入框视图
    func inputTextView() {
        //背景视图
        inputToolBarV = UIView(frame: CGRect(x: 0, y: screenH, width: screenW, height: 44))
        inputToolBarV.backgroundColor = UIColor().colorWithHex(0xF0F0F0)
     
        
        //添加一个输入框
        inputTextF = UITextField(frame: CGRect(x: 8, y: 0, width: screenW - 66, height: 44))
        inputTextF.placeholder = "回复就是一种鼓励！"
        inputTextF.borderStyle = .roundedRect
        //右边清除按钮
        inputTextF.clearButtonMode = .always
        inputTextF.font = UIFont.systemFont(ofSize: 15)
        inputTextF.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        inputToolBarV.addSubview(inputTextF)
        
        //添加一个确定按钮
        let suerBtn = UIButton(type: .custom)
        suerBtn.frame = CGRect(x: screenW - 58, y: 0, width: 50, height: 44)
        suerBtn.setTitle("确定", for: .normal)
        suerBtn.setTitleColor(#colorLiteral(red: 0, green: 0.6925219297, blue: 0.9319912791, alpha: 1), for: .normal)
        suerBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        //添加按钮的监听回调方法
        suerBtn.addTarget(self, action: #selector(sureBtnClicked), for: .touchUpInside)
        inputToolBarV.addSubview(suerBtn)
        //添加输入工具栏到窗口视图
        let KWindow = UIApplication.shared.keyWindow
        KWindow?.addSubview(inputToolBarV)
    }
    //Mark: - 确定按钮的监听回调方法
    @objc fileprivate func sureBtnClicked() {
        //退出键盘
        inputTextF.resignFirstResponder()
        //获取输入内容
        let inputText = inputTextF.text!
//        print(inputText)
        if inputText == "" {
            HSAlertView.bottomAlertView("输入内容不能为空")
            return
        }
        //获得接口
        let url = "ZH-schoolname-S-submitJXReplay"
        //获得参数
        //用户key
        let key = userInfo["key"] ?? 0
        //通知Id
        let messageVM = currentCell.messageVM
        let not_id = messageVM?.message.not_id ?? 0
        //设置参数字典
        let param = ["key":key,"id":not_id,"content":inputText,"user_type":2]
        //请求
        HSNetWorkTools.shared.downloadData(url: url, parameters: param) {[weak self] (data, err) in
//            print(data)
            guard let data = data as? NSDictionary else {
                
                HSAlertView.bottomAlertView("网络异常，请重新连接")
                
                return
            }
            switch data["result"] as! Int {
            case 0:
            //获得回复列表字典数组
                let listArray = data["data"] as! [[String: Any]]
                var modelArray = [HSReplaylistModal]()
                    for dict in listArray {
                        let listModal = HSReplaylistModal(dict: dict)
                        modelArray.append(listModal)
                }
                //将新的模型数组赋值给视图模型中的模型属性
                let message = messageVM?.message
                message?.replaylist = modelArray
                messageVM?.message = message!
                //刷新视图
                self?.tableView.reloadData()
                //获得当前cell的indexpath
//                guard  let indexPath = self?.tableView.indexPath(for: (self?.currentCell)!) else {
//                    
//                    return
//                }
//                self?.tableView.reloadRows(at: [indexPath], with: .automatic)
            case 1:
                    HSAlertView.bottomAlertView("数据发送异常")
            default:
            break
            }
            
          
            
        }
        
        
        
    }
    
    ///回复按钮的点击回调
    func replayBtnClicked(cell: HSMessageTableViewCell) {
        //用于记录点击的是否为同一个
        let cellEqual = (currentCell == cell)
        //记录当前cell
        currentCell = cell
        //设置输入框为第一响应者，触发键盘自动弹出
        if inputTextF.isFirstResponder {
            if cellEqual {
                
            inputTextF.resignFirstResponder()
            }
           
        } else {
             inputTextF.becomeFirstResponder()
        }
        if !cellEqual {
            inputTextF.becomeFirstResponder()
        }
        
    }
    ///键盘通知的回调方法
    func notificationWithKeyboard(notify:Notification) {
        print(notify.userInfo)
        //获取键盘的Y值
        let keyboardRect = notify.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue
        
        let keyboardY = keyboardRect?.cgRectValue.minY ?? 0
        print(keyboardY)
        //取反
        isKeyboardShow = !(keyboardY >= screenH)
        //计算工具栏的Y值
        let toolBarY = isKeyboardShow ? (keyboardY - 44) : (keyboardY + 44)
//        print(toolBarY)
        inputToolBarV.frame.origin.y = toolBarY
        
        
        //适配表格试图高度跟随键盘高度
        //获得当前窗口视图
        let kWindow = UIApplication.shared.keyWindow
        //获得cell参照于窗口的frame
        let cellFrame = kWindow?.convert(currentCell.frame, from: tableView)
//        print(cellFrame)
        //获得cell的底部Y值
        let cellMaxY = cellFrame?.maxY ?? 0
        //计算表格视图的偏移量
        let offSetY = cellMaxY - toolBarY
        if offSetY > 0 {
            //获得表格试图当前的偏移量
            let currentOffSetY = tableView.contentOffset.y
            //重新设置
            tableView.setContentOffset(CGPoint(x: 0, y: offSetY + currentOffSetY), animated: true)
        }
    }
    //滚动退出编辑事件
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        inputTextF.resignFirstResponder()
    }
}
